package com.violet.uaa.server.security.handler;

import cn.hutool.json.JSONUtil;
import com.violet.common.constant.business.CodeEnum;
import com.violet.common.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Author: wqf
 * @Date: 2023/07/10
 * @Description: 登录失败后续处理
 */
@Slf4j
@Component
public class VioFailureHandler implements AuthenticationFailureHandler {
    /**
     * Called when an authentication attempt fails.
     *
     * @param request   the request during which the authentication attempt occurred.
     * @param response  the response.
     * @param exception the exception which was thrown to reject the authentication
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.info("登陆失败，当前用户信息：{}", JSONUtil.toJsonStr(request.getParameter("username")));
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        try (ServletOutputStream ous = response.getOutputStream()) {
            Result<Object> responseData = Result.failure(CodeEnum.FORBIDDEN.getCode(), "用户名或密码错误");
            response.setStatus(HttpStatus.FORBIDDEN.value());
            ous.write(JSONUtil.toJsonStr(responseData).getBytes(StandardCharsets.UTF_8));
        }
    }
}
